<!-- 纵向布局 -->
<template>
  <el-container class="layout">
    <el-aside>
      <div class="aside-box" :style="{ width: isCollapse ? '65px' : '210px' }">
        <div class="logo flx-center">
          <img class="logo-img" src="https://edu2.cqzhxt.com/assets/logo-38d330c0.png" alt="logo" />
          <span v-show="!isCollapse" class="logo-text">{{ title }}</span>
        </div>
        <el-scrollbar>
          <!-- 二级菜单栏 -->
          <el-aside :class="{ 'not-aside': !subMenuList.length }" :style="{ width: isCollapse ? '65px' : '210px' }"
            :default-active="activeMenu" :collapse="isCollapse" :unique-opened="accordion" :collapse-transition="false">
            <!-- <SubMenu :menu-list="subMenuList" @menu-select="handleSubMenuSelect" /> -->
            <!-- <el-menu :router="false" :default-active="activeMenu" :collapse="isCollapse" :unique-opened="accordion"
              :collapse-transition="false"> -->
            <SubMenu :menu-list="subMenuList" @menu-select="handleSubMenuSelect"
              :secondLevelMenuKey="secondLevelMenuKey" :thirdLevelMenuKey="thirdLevelMenuKey" />
            <!-- </el-menu> -->
          </el-aside>
        </el-scrollbar>
      </div>
    </el-aside>
    <el-container>
      <el-header>
        <ToolBarLeft />
        <div class="header-right">
          <!-- 顶部一级菜单栏 -->
          <TopMenu :menu-list="menuList" @menu-select="handleMenuSelect" :firstActiveKey="firstActiveKey" />
          <ToolBarRight />
        </div>
      </el-header>
      <Main @tabData="handleTabData" @to-home="handleToHome" />
    </el-container>
  </el-container>
</template>

<script setup lang="ts" name="layoutVertical">
import { computed, nextTick, ref, watch } from "vue";
import { useRoute } from "vue-router";
import { useAuthStore } from "@/stores/modules/auth";
import { useGlobalStore } from "@/stores/modules/global";
import Main from "@/layouts/components/Main/index.vue";
import ToolBarLeft from "@/layouts/components/Header/ToolBarLeft.vue";
import ToolBarRight from "@/layouts/components/Header/ToolBarRight.vue";
import SubMenu from "@/layouts/components/Menu/SubMenu.vue";
import { useRouter } from 'vue-router';
import TopMenu from "@/layouts/components/Header/components/TopMenu.vue"
import { HOME_URL } from "@/config";
import { useTabsStore } from "@/stores/modules/tabs";


const title = import.meta.env.VITE_GLOB_APP_TITLE;

const route = useRoute();
const authStore = useAuthStore();
const globalStore = useGlobalStore();
const accordion = computed(() => globalStore.accordion);
const isCollapse = computed(() => globalStore.isCollapse);
// const menuList = computed(() => authStore.showMenuListGet);
const menuList = computed(() => authStore.authMenuListGet);
const activeMenu = computed(() => (route.meta.activeMenu ? route.meta.activeMenu : route.path) as string);

const tabStore = useTabsStore();
const router = useRouter();
const subMenuList = ref<Menu.MenuOptions[]>([]);
const firstActiveKey = ref('/home/index')
const secondLevelMenuKey = ref('')
const thirdLevelMenuKey = ref('')

const handleMenuSelect = (path: string) => {
  const selectedMenu = menuList.value.find(item => item.path === path);
  if (selectedMenu && selectedMenu.children) {
    subMenuList.value = selectedMenu.children;

    if (selectedMenu.children.length > 0 && selectedMenu.children[0].path) {
      secondLevelMenuKey.value = selectedMenu.children[0].path
    }

    if (selectedMenu.children[0] && selectedMenu.children[0].children && selectedMenu.children[0].children[0] && selectedMenu.children[0].children[0].path) {
      thirdLevelMenuKey.value = selectedMenu.children[0].children[0].path
    }
  } else {
    subMenuList.value = [];
  }
  router.push(path);
};

//获取标签页数据
const handleTabData = (data: any) => {

  //回到首页
  if (data.name === '/home/index') {
    handleToHome()
  }
  //根据data.name找到对应的一级菜单
  const firstLevelMenu: any = menuList.value.find(item => item.children?.some(child => child.path === data.name))
  //根据data.name找到对应的二级菜单
  const secondLevelMenu: any = menuList.value.find(item => item.children?.some(child => child.children?.some(_child => _child.path === data.name)))

  if (firstLevelMenu && firstLevelMenu.path) {
    firstActiveKey.value = firstLevelMenu.path
    handleMenuSelect(firstLevelMenu.path)
    //更新二级菜单
    secondLevelMenuKey.value = data.name
  }

  if (secondLevelMenu && secondLevelMenu.path) {
    firstActiveKey.value = secondLevelMenu.path
    subMenuList.value = secondLevelMenu.children
    thirdLevelMenuKey.value = data.name
  }
}

const handleToHome = () => {
  firstActiveKey.value = HOME_URL
  subMenuList.value = []
  // handleMenuSelect(HOME_URL)
}

const handleSubMenuSelect = (path: string) => {
  router.push(path);
};

function updateSecondLevelMenu(firstLevel: any) {
  const selectedMenu = menuList.value.find((item) => item.path === firstLevel.path);
  if (selectedMenu && selectedMenu.children) {
    subMenuList.value = selectedMenu.children;
  }
}

//根据路由查找到路由
function findParentRoutes(routes: any[], path: string): { firstLevel: any, secondLevel: any, thirdLevel: any } {
  let firstLevel: any = null;
  let secondLevel: any = null;
  let thirdLevel: any = null;

  function findRoute(routes: any[], pathSegments: string[]) {
    const currentSegment = pathSegments.shift();
    if (!currentSegment) return;

    for (const route of routes) {
      if (route.path === `/${currentSegment}`) {
        if (pathSegments.length == 1) {
          firstLevel = route;
          return;
        }
        if (route.children) {
          if (pathSegments.length == 2) {
            firstLevel = route;
            secondLevel = route.children.find(child => child.path === `/${currentSegment}/${pathSegments[0]}/${pathSegments[1]}`) || null;
            return;
          }
          if (pathSegments.length == 3) {
            firstLevel = route;
            secondLevel = route.children.find(child => child.path === `/${currentSegment}/${pathSegments[0]}`) || null;
            if (secondLevel && secondLevel.children) {
              thirdLevel = secondLevel.children.find(child => child.path === `/${currentSegment}/${pathSegments[0]}/${pathSegments[1]}/${pathSegments[2]}`) || null;
            }
            return;
          }
          findRoute(route.children, pathSegments);
        }
      }
    }
  }

  findRoute(routes, path.split('/').slice(1));

  return { firstLevel, secondLevel, thirdLevel };
}

watch(
  () => route.path,
  (newPath) => {
    if (newPath === HOME_URL) {
      handleToHome()
    } else {
      const { firstLevel, secondLevel, thirdLevel } = findParentRoutes(menuList.value, newPath);
      if (firstLevel && secondLevel && thirdLevel) {
        firstActiveKey.value = firstLevel?.path;
        secondLevelMenuKey.value = secondLevel.path;
        thirdLevelMenuKey.value = thirdLevel.path;
        router.push(thirdLevel.path);
        updateSecondLevelMenu(firstLevel);
      } else if (firstLevel && secondLevel && thirdLevel === null) {
        firstActiveKey.value = firstLevel?.path;
        secondLevelMenuKey.value = secondLevel.path;
        router.push(secondLevel.path);
        updateSecondLevelMenu(firstLevel);
      } else if (firstLevel && secondLevel === null && thirdLevel === null) {
        firstActiveKey.value = firstLevel?.path;
        secondLevelMenuKey.value = firstLevel?.path;
        thirdLevelMenuKey.value = newPath;
        updateSecondLevelMenu(firstLevel);
      }
    }
  },
  { immediate: true }
);

</script>

<style scoped lang="scss">
@import "./index.scss";
</style>
